/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util;

import org.hibernate.HibernateException;
import org.hibernate.cfg.Configuration;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 * Hibernate Utility class with a convenient method to get Session Factory object.
 *
 */
public class HibernateUtil {

    private static final SessionFactory sessionFactory;
    private static final ThreadLocal session = new ThreadLocal();
    private static final ThreadLocal transaction = new ThreadLocal();

        static {
            try {
                sessionFactory = new Configuration().configure().buildSessionFactory();
            } catch (HibernateException he) {
                System.err.println("Ocurrió un error en la inicialización de la SessionFactory: " + he);
                throw new ExceptionInInitializerError(he);
            }
        }

    public static Session getSession() {
        Session sesion = (Session) HibernateUtil.session.get();
        if (sesion == null || !sesion.isOpen()) {
            sesion = sessionFactory.openSession();
            HibernateUtil.session.set(sesion);
        }
        return sesion;
    }
    
    public static void closeSession(Session sesion) {
        if (sesion != null) {
            try {
                sesion.close();
            } catch (HibernateException ignored) {
                System.err.println("No se pudo cerrar la sesión: " + ignored);
            }
        }
    }
        
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    
}